package yxy.game.pm2.command.chibi;

import yxy.cherry.data.bean.chibidate;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ChibiMessage;
import yxy.game.pm2.module.chibi.ChibiHandle;
import yxy.game.pm2.module.chibi.ChibiModule;

/** 火烧赤壁 火烧赤壁挑战三消 */
@MessageType(proto = Command.ChibiChanllenge, classtype = ChibiMessage.ChibiChanllengeRequest.class)
public class CMD_ChibiChanllenge extends Command<ChibiMessage.ChibiChanllengeRequest> {

	@Override
	public void execute(MessageSource messageSource, ChibiMessage.ChibiChanllengeRequest request) {
		String playerCode = messageSource.getTag();
		int id = request.getId();

		ChibiMessage.ChibiChanllengeResponse.Builder response = ChibiMessage.ChibiChanllengeResponse.newBuilder();

		ChibiHandle handle = new ChibiHandle();
		if (handle.isBattling(playerCode)) {
			send(messageSource, response, Result.BattleIsRunning);// 还有正在进行中的战斗
			return;
		}

		chibidate data = ChibiHandle.data(id);
		if (data == null) {
			send(messageSource, response, Result.ParamError);
			return;
		}
		ChibiModule module = ChibiModule.get(playerCode);
		Result result = handle.checkCanBattle(module, data);
		if (!result.equals(Result.Success)) {
			send(messageSource, response, result);
			return;
		}

		try {
			response.setBattle(handle.battleResponse(module, data));
			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, ChibiMessage.ChibiChanllengeResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}